package com.mybatis.basic.aop;

import java.lang.reflect.Method;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import com.mybatis.basic.annotation.rediscache.RedisCacheClear;
import com.mybatis.basic.service.RedisService;

@Aspect
@Component
public class RedisCacheClearAOP {
	
	private static final Logger log = Logger.getLogger(RedisCacheAOP.class);

	@Resource
	private RedisService redisService;

	@Pointcut("@annotation(com.mybatis.basic.annotation.rediscache.RedisCacheClear)")
	public void redisCacheClear() {
		log.info("****** 执行RedisCacheClear ******");
	}

	@Around("redisCacheClear()")
	public Object redisCacheAround(ProceedingJoinPoint joinPoint) {
		Object obj = null;
		try {
			//得到代理方法
			Method method = ((MethodSignature)joinPoint.getSignature()).getMethod();
			//得到代理方法上的@RedisCache注解
			RedisCacheClear redisCacheClear = method.getAnnotation(RedisCacheClear.class);
			//获取注解上的参数
			String name = redisCacheClear.group();
			String key = redisCacheClear.key();
			if(!StringUtils.isEmpty(name)) {
				if(!StringUtils.isEmpty(key)) {
					redisService.delByHash(name, key);
				}else {
					redisService.del(name);
				}
			}else {
				if(!StringUtils.isEmpty(key)) {
					redisService.del(key);
				}else {
					throw new NullPointerException("[@RedisCacheClear =>> 删除key ] group AND key 不能同时为空");
				}
			}
		} catch (Throwable e) {
			e.printStackTrace();
			log.error(e);
		} finally {
			try {
				obj = joinPoint.proceed(joinPoint.getArgs());
			} catch (Throwable e) {
				e.printStackTrace();
			}
		}
		return obj;
	}
}
